<template>
  <div class="min-h-screen py-8">
    <div class="container mx-auto px-4">
      <!-- 页面标题 -->
      <div class="mb-8">
        <h1 class="text-3xl md:text-4xl font-bold text-gray-800">
          图书列表
        </h1>
        <p class="text-gray-500 mt-2">
          浏览我们的精选图书
        </p>
      </div>
      
      <!-- 筛选和搜索 -->
      <div class="bg-white rounded-lg shadow-sm p-4 mb-8">
        <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <!-- 搜索框 -->
          <div class="relative flex-1">
            <input 
              v-model="searchQuery"
              type="text" 
              placeholder="搜索图书、作者或ISBN..." 
              class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
            <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
          </div>
          
          <!-- 分类筛选 -->
          <div class="flex-1">
            <select 
              v-model="selectedCategory"
              class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="">所有分类</option>
              <option v-for="category in categories" :key="category" :value="category">
                {{ category }}
              </option>
            </select>
          </div>
          
          <!-- 排序 -->
          <div class="flex-1">
            <select 
              v-model="sortBy"
              class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="default">默认排序</option>
              <option value="priceAsc">价格: 低到高</option>
              <option value="priceDesc">价格: 高到低</option>
              <option value="rating">评分: 高到低</option>
            </select>
          </div>
        </div>
      </div>
      
      <!-- 图书列表 -->
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
        <div 
          v-for="book in filteredBooks" 
          :key="book.id" 
          class="bg-white rounded-lg shadow-sm overflow-hidden group hover:shadow-md transition-shadow"
        >
          <!-- 图书封面 -->
          <div class="h-64 overflow-hidden bg-gray-100 flex items-center justify-center">
            <img 
              :src="book.cover" 
              alt="Book cover" 
              class="h-full w-auto group-hover:scale-105 transition-transform"
            >
          </div>
          
          <!-- 图书信息 -->
          <div class="p-4">
            <div class="flex justify-between items-start mb-1">
              <h3 class="font-medium text-gray-900 line-clamp-2 group-hover:text-blue-600 transition-colors">
                <router-link :to="`/books/${book.id}`">{{ book.title }}</router-link>
              </h3>
            </div>
            
            <p class="text-sm text-gray-500 line-clamp-1 mb-2">{{ book.author }}</p>
            
            <!-- 评分 -->
            <div class="flex items-center mb-3">
              <div class="flex text-yellow-400 text-xs">
                <i class="fa fa-star"></i>
                <i class="fa fa-star"></i>
                <i class="fa fa-star"></i>
                <i class="fa fa-star"></i>
                <i class="fa fa-star-half-o"></i>
              </div>
              <span class="ml-1 text-xs text-gray-500">{{ book.rating }}</span>
            </div>
            
            <!-- 价格和操作 -->
            <div class="flex justify-between items-center">
              <span class="font-medium text-blue-600">¥{{ book.price.toFixed(2) }}</span>
              <button 
                @click="addToCart(book)" 
                class="text-blue-600 hover:text-blue-800 hover:bg-blue-50 p-2 rounded-md transition-colors"
              >
                <i class="fa fa-shopping-cart"></i>
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-if="filteredBooks.length === 0" class="text-center py-16">
        <div class="w-20 h-20 mx-auto mb-4 text-gray-300">
          <i class="fa fa-book text-5xl"></i>
        </div>
        <h3 class="text-lg font-medium text-gray-700 mb-2">没有找到匹配的图书</h3>
        <p class="text-gray-500 mb-6">尝试使用不同的搜索条件或浏览其他分类</p>
        <button 
          @click="resetFilters" 
          class="inline-flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md transition-colors"
        >
          重置筛选条件
        </button>
      </div>
      
      <!-- 分页 -->
      <div v-if="filteredBooks.length > 0" class="mt-12 flex justify-center">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[8, 16, 24]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredBooks.length"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { useCartStore } from '@/stores/cartStore';
import { getAllBooks } from '@/services/bookService';

// 获取购物车状态
const cart = useCartStore();

// 初始化状态
const books = ref([]);
const searchQuery = ref('');
const selectedCategory = ref('');
const sortBy = ref('default');
const pageSize = ref(8);
const currentPage = ref(1);

// 获取所有图书
const fetchBooks = async () => {
  try {
    books.value = await getAllBooks();
  } catch (error) {
    console.error('Failed to fetch books:', error);
    // 显示错误提示
    ElMessage.error('获取图书列表失败');
  }
};

// 页面加载时获取图书数据
fetchBooks();

// 获取所有分类
const categories = computed(() => {
  const categorySet = new Set();
  books.value.forEach(book => categorySet.add(book.category));
  return Array.from(categorySet);
});

// 过滤和排序图书
const filteredBooks = computed(() => {
  let result = [...books.value];
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(book => 
      book.title.toLowerCase().includes(query) || 
      book.author.toLowerCase().includes(query) ||
      book.isbn.toLowerCase().includes(query)
    );
  }
  
  // 分类过滤
  if (selectedCategory.value) {
    result = result.filter(book => book.category === selectedCategory.value);
  }
  
  // 排序
  switch (sortBy.value) {
    case 'priceAsc':
      result.sort((a, b) => a.price - b.price);
      break;
    case 'priceDesc':
      result.sort((a, b) => b.price - a.price);
      break;
    case 'rating':
      result.sort((a, b) => b.rating - a.rating);
      break;
    default:
      // 默认排序（按ID）
      result.sort((a, b) => a.id - b.id);
  }
  
  return result;
});

// 分页后的图书
const paginatedBooks = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredBooks.value.slice(start, end);
});

// 添加到购物车
const addToCart = (book) => {
  cart.addToCart(book);
  // 显示添加成功提示
  ElMessage.success('已添加到购物车');
};

// 重置筛选条件
const resetFilters = () => {
  searchQuery.value = '';
  selectedCategory.value = '';
  sortBy.value = 'default';
  currentPage.value = 1;
};

// 监听筛选条件变化，重置分页
watch([searchQuery, selectedCategory, sortBy], () => {
  currentPage.value = 1;
});

// 处理每页数量变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
};

// 处理当前页变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};
</script>

<style scoped>
/* 可以添加自定义样式 */
</style>
    